package com.tao.common.creo.Utils;

import com.tao.common.creo.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Map;
public class JwtUtils {
    /**
     * ⽣成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret) {
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    public static String getUserKey(Claims claims) {
        return toStr(claims.get(JwtConstants.USER_KEY));
    }

    public static String getUUID(Claims claims) {
        if(claims == null) return null;
        return String.valueOf(claims.get(JwtConstants.USER_KEY));
    }

    public static String getUserId(Claims claims) {
        return toStr(claims.get(JwtConstants.USER_ID));
    }


    private static String toStr(Object values) {
        if (values == null) {
            return "";
        }
        return values.toString();
    }


    /**
     * 从令牌中获取数据
     *
     * @param token  令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        try {
            Claims jwt = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return jwt;
        }catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEsInVzZXJLZXkiOiJhYjNlMWQ3NS05N2I1LTQwZTItOWY0Ny0yNDY5YzcxYjZlMGUifQ.FiEFypiwbyeM7z1hJq8T3RUYcOJIioibxKoHJg9yhTi6OISxMdbfd6-NZwZ1UI8HhK-4U-hDAwTUw5b4lujEIQ";
        String secret = "djsaflnvlkasdjflkadfj";
        Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        System.out.println(body);
    }
}
